package com.gz.controller;
import java.util.List;

import com.gz.common.CouponService;
import com.gz.common.IntegralrecordService;
import com.gz.common.ProductService;
import com.gz.common.UserService;
import com.gz.common.model.Coupon;
import com.gz.common.model.Integralrecord;
import com.gz.common.model.User;
import com.gz.utils.Response;
import com.jfinal.core.Controller;
/**
 * 优惠劵控制器
 * @author 86173
 *
 */
public class CouponController extends Controller{
	
	/**
	 * 显示所有优惠劵
	 * author 绝爷
	 * @return CouponList
	 * @URL http://localhost:8080/cms-api/coupon/getCouponList
	 */
	public void getCouponList() {
		List<Coupon> couponList =ProductService.getService().getCouponList();
		if(couponList!=null&&couponList.size()>0) {
			renderJson(Response.responseJson(1005,"成功！",couponList));
		}else {
			renderJson(Response.responseJson(1006,"本期没有优惠劵可兑换",null));
		}
	}
	
	/**
	 *  	兑换优惠劵
	 * @author 绝爷
	 * @param couponId=?
	 * @param userId
	 * @URL http://localhost:8080/cms-api/coupon/exchangeCoupon
	 */
	public void exchangeCoupon() {
		Integer couponId = getParaToInt("id");
		Coupon coupon = CouponService.getCouponService().findIntegral(couponId);
		/*判断该优惠劵是否存在*/
		if(coupon==null) {
			renderJson(Response.responseJson(1007,"兑换卷信息错误！"));
			return;
		}
		/*获取该优惠劵兑换所需积分*/
		Integer integral = coupon.getIntegral();
		/*获取用户信息*/
		Integer userId = getParaToInt("userId");
		User user = UserService.getService().findUserId(userId);
		/*消费积分*/
		Integer consumption = user.getConsumption();
		/*提现积分*/
		Integer amount = user.getAmountS();
		/*判断消费积分是否足够兑换*/
		if(consumption>=integral) {
			consumption=consumption-integral;
		/*判断消费积分加上提现积分是否足够兑换*/	
		}else if((consumption+amount)>=integral) {
			amount=amount-(integral-consumption);
			consumption=0;
		}else {
			renderJson(Response.responseJson(1006,"积分不够兑换此优惠劵！"));
			return;
		}
		user.setConsumption(consumption);
		user.setAmountS(amount);
		//积分扣除成功返回true
		if(CouponService.getCouponService().changeCoupon(user)) {
			if(CouponService.getCouponService().addUserCoupon(user, coupon)) {
				/*新增积分使用记录*/
				Integralrecord integralrecord = new Integralrecord();
				integralrecord.setUserid(user.getId());
				integralrecord.setType(3);
				integralrecord.setUseintegral(integral);
				integralrecord.setGetintegral(0);
				if(IntegralrecordService.getService().xinZengJiFeng(integralrecord)) {
					renderJson(Response.responseJson(1008,"优惠劵兑换成功!"));
				}else {
					renderJson(Response.responseJson(1009,"优惠劵兑换成功!但新增积分使用记录失败！"));
				}
				return;
			}
		}
		renderJson(Response.responseJson(1005,"积分扣除失败！"));
	}

}
